﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WeatherComm
{
    public class HttpHelper
    {
        public static string GetUrl2Html(string Url, string encoder)
        {
            WebRequest wReq = null;
            WebResponse wResp = null;
            var s = "";
            try
            {
                wReq = WebRequest.Create(Url);
                wReq.Timeout = 2000;
                wResp = wReq.GetResponse();
                var respStream = wResp.GetResponseStream();
                if (respStream != null)
                    using (var reader = new StreamReader(respStream, Encoding.GetEncoding(encoder)))
                    {
                        s = reader.ReadToEnd();
                        reader.Close();
                    }
                respStream?.Close();
                wResp.Close();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                wReq?.Abort();
                wResp?.Close();
            }
            return s;
        }

        public static async Task<string> GetHtmlAsync(string Url)
        {
            var client = new HttpClient();
            try
            {
                client.Timeout = new TimeSpan(0, 0, 0, 5);

                client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent",
                     GetDefaultUserAgent());

                //var response = await client.GetAsync(Url);
                //response.EnsureSuccessStatusCode();
                //var responseBody = await response.Content.ReadAsStringAsync();
                //var a1=await Task.Run(async () =>
                //{
                //    var rs = await client.GetStringAsync(Url);
                //    return rs;
                //});

                var responseBody = await client.GetStringAsync(Url);
                //var t = client.GetStringAsync(Url);
                //t.Wait();
                return responseBody;
            }
            catch (Exception e)
            {
                Log.WriteLog(e.Message);
            }
            return null;
        }
        public static async Task<string> GetHtmlAsync(string Url, string encoder)
        {
            var client = new HttpClient();
            try
            {
                client.Timeout = new TimeSpan(0, 0, 0, 5);

                client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent",
                    GetDefaultUserAgent());

                var buffer = await client.GetByteArrayAsync(Url);
                var ed = Encoding.GetEncoding(encoder);
                var responseBody = ed.GetString(buffer.ToArray(), 0, buffer.Length - 1);
                return responseBody;
            }
            catch (Exception e)
            {
                Log.WriteLog(e.Message);
            }
            return "";
        }
        /// <summary> 
        /// 获取IE默认UserAgent的方法 
        /// </summary> 
        private static string GetDefaultUserAgent()
        {
            var wb = new WebBrowser();
            wb.Navigate("about:blank");
            while (wb.IsBusy) Application.DoEvents();
            if (wb.Document == null || wb.Document.Window == null) return "";
            var window = wb.Document.Window.DomWindow;
            var wt = window.GetType();
            var navigator = wt.InvokeMember("navigator", BindingFlags.GetProperty,
                null, window, new object[] { });
            var nt = navigator.GetType();
            var userAgent = nt.InvokeMember("userAgent", BindingFlags.GetProperty,
                null, navigator, new object[] { });
            return userAgent.ToString();
        }
    }
}
